package com.kanshu.ksgb.fastread.doudou.module.book.activity

import android.app.Activity
import android.app.Service
import android.content.Context
import android.os.Bundle
import android.os.Message
import android.os.Vibrator
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.dl7.recycler.adapter.BaseQuickAdapter
import com.dl7.recycler.adapter.BaseViewHolder
import com.dl7.recycler.helper.RecyclerViewHelper
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.base.basemvp.IGenrialMvpView
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.WeakHandler
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager
import com.kanshu.ksgb.fastread.doudou.common.business.utils.BookUtils
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.util.*
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookPresenter
import com.kanshu.ksgb.fastread.doudou.module.book.utils.NeedForAnim.HAND_ANIM_END
import com.kanshu.ksgb.fastread.doudou.module.book.utils.NeedForAnim.HAND_ANIM_START
import com.kanshu.ksgb.fastread.doudou.module.book.utils.ShakeListener
import kotlinx.android.synthetic.main.activity_shake.*

/**
 * Description:摇一摇
 * @author EvanHe
 * CreateTime: 2018/11/26 17:01
 */
const val AD_MAX_POSITION = 3

@Route(path = ARouterConfig.BOOK_SHAKE)
class ShakeActivity : BaseActivity(), WeakHandler.IHandler, IGenrialMvpView<BaseResult<List<BookInfo>>> {
    private var mView: LinearLayout? = null
    //震动器
    private var mVibrator: Vibrator? = null
    internal var rotate: Animation? = null
    //手机摇晃的监听器
    private var mShakeListener: ShakeListener? = null
    private var shakeListener: ShakeListener.OnShakeListenerCallBack? = null
    private var handler: WeakHandler? = null
    private var isRefreshFinish: Boolean = true

    private val bookPresenter = BookPresenter(lifeCyclerSubject)
    private var shakeBookListAdapter: ShakeBookListAdapter? = null
    private var list: MutableList<BookInfo> = mutableListOf()
    private val sex = MMKVUserManager.getInstance().loginSex

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shake)
        initData()
        initShake()

        iv_shake.setOnClickListener {
            //点击按钮 开始 摇一摇
            startShake()
        }
    }

    private fun initData() {
        mTitle.setTitle("摇一摇")
        mView = findViewById(R.id.shake_layout)
        shakeBookListAdapter = ShakeBookListAdapter(this, list)
        RecyclerViewHelper.initRecyclerViewV(this, recycler_view, shakeBookListAdapter)
        SwipeRefreshHelper.init(swipe_refresh, {})
        swipe_refresh.setEnableRefresh(false)
        bookPresenter.setShakeBookListView(this)
        bookPresenter.getShakeBook("yaoyiyao", sex)
    }

    private fun initShake() {
        mVibrator = getSystemService(Service.VIBRATOR_SERVICE) as Vibrator?
        rotate = AnimationUtils.loadAnimation(this, R.anim.shake_rotate_anim)
        mShakeListener = ShakeListener(this)
        shakeListener = ShakeListener.OnShakeListenerCallBack {
            //获取手机晃动监听  开始 摇一摇
            startShake()
        }
        mShakeListener?.setOnShakeListener(shakeListener)
        handler = WeakHandler(this)
    }

    //开始摇一摇动画
    private fun startShake() {
        handler?.sendEmptyMessage(HAND_ANIM_START)
        mShakeListener?.stop()
        mVibrator?.vibrate(longArrayOf(200, 300, 200, 300, 200), -1)
        //间隔1.2s,发送一个空消息，告诉handler已经结束摇动了//避免了多次请求处理
        handler?.sendEmptyMessageDelayed(HAND_ANIM_END, 1200)
        DisplayUtils.visible(progressBar)
    }

    private fun getShakeData() {
        //首先判断数据是否加载完成，其次判断3s延迟加载
        if (isRefreshFinish) {
            isRefreshFinish = false
            bookPresenter.getShakeBook("yaoyiyao", sex)
        } else {
            DisplayUtils.gone(progressBar)
        }
    }

    override fun showContent(t: BaseResult<List<BookInfo>>?) {
        t?.result?.data?.also {
            if (Utils.isEmptyList(it)) {
                return@also
            }
            list.clear()
            list.addAll(it)
            val index = if (it.size < AD_MAX_POSITION) {
                it.size
            } else {
                AD_MAX_POSITION
            }
            shakeBookListAdapter?.setIndexV(index)
            shakeBookListAdapter?.notifyDataSetChanged()
        }
        isRefreshFinish = true
        DisplayUtils.gone(progressBar)
    }

    override fun showError(errCode: Int, errDesc: String?) {
        isRefreshFinish = true
        DisplayUtils.gone(progressBar)
    }

    override fun handleMsg(msg: Message?) {
        when (msg?.what) {
            HAND_ANIM_START -> {
                mView?.startAnimation(rotate)
            }
            HAND_ANIM_END -> {
                mShakeListener?.start()
                getShakeData()
            }
            else -> {
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mShakeListener?.start()
    }

    override fun onPause() {
        mShakeListener?.stop()
        super.onPause()
    }

    override fun onStop() {
        mShakeListener?.stop()
        super.onStop()
    }

    override fun onDestroy() {
        handler?.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    class ShakeBookListAdapter(val context: Context, data: List<BookInfo>?) : BaseQuickAdapter<BookInfo>(context, data) {
        var adContainer: ViewGroup? = null
        var index: Int = -1

        fun setIndexV(i: Int) {
            if (i > 0)
                index = i - 1
        }

        override fun attachLayoutRes(): Int {
            return R.layout.item_shake_book_layout
        }

        override fun convert(holder: BaseViewHolder, item: BookInfo?, position: Int) {
            item?.run {
                GlideImageLoader.load(cover_url, holder.getView(R.id.cover))
                holder.setText(R.id.book_title, book_title).setText(R.id.book_desc, book_intro)
                        .setText(R.id.author, author_name).setText(R.id.book_label, BookUtils.getBookLabel(this))
                        .setText(R.id.book_status, BookUtils.getBookLabel(this))
                holder.getView<RelativeLayout>(R.id.root_container).setOnClickListener {
                    ARouterUtils.toActivity(ARouterConfig.BOOK_DETAIL, "book_id", book_id)
                }
                if (index == position) {
                    adContainer = holder.getView(R.id.adContainer)
                    DisplayUtils.visible(adContainer, holder.getView(R.id.divider))
                    getAdData()
                } else {
                    DisplayUtils.gone(holder.getView(R.id.adContainer), holder.getView(R.id.divider))
                }
            }
        }

        private fun getAdData() {
            AdUtils.destroyAd(adContainer)
            AdUtils.fetchAdUtil(context as Activity, adContainer, null, ADConfigBean.POSITION_SHAKE_FEED, AdStyleBean.IMAGE_TEXT_STYLE, 0, object : BaseAdListener {
                override fun onAdLoadSucceeded(view: View?) {
                }

                override fun onAdLoadFailed() {
                }

                override fun onAdClicked() {
                }

                override fun onADClosed() {
                }

                override fun onBackAd(ad: Any) {
                }
            })
        }
    }
}